package com.solocredit.finance.ui.splash.act

import android.Manifest
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import com.solocredit.finance.R
import com.solocredit.finance.base.utils.ImageUtil
import com.solocredit.finance.base.utils.helper.ActivityStackManager
import com.solocredit.finance.base.utils.permission.OnPermissionCallback
import com.solocredit.finance.base.utils.permission.XXPermissions
import com.solocredit.finance.config.MullaConfigs
import com.solocredit.finance.databinding.ActMullaSplashBinding
import com.solocredit.finance.http.ApiService
import com.solocredit.finance.http.HttpDnsV2
import com.solocredit.finance.http.HttpHelper
import com.solocredit.finance.mvp.MvpAct
import com.solocredit.finance.ui.main.act.MullaMainAct
import com.solocredit.finance.ui.splash.impl.MullaSplashPresenterImpl
import com.solocredit.finance.ui.splash.view.IMullaSplashView
import com.solocredit.finance.ui.user.act.MullaUserLoginAct
import com.solocredit.finance.utils.dialog.PermissionReasonDialog
import com.solocredit.finance.utils.dialog.VersionUpdateDialog
import com.solocredit.finance.utils.event.MullaEventType
import com.solocredit.finance.utils.helper.MullaAnalysisHelper
import com.solocredit.finance.utils.helper.MullaCustomConfigsHelper
import com.solocredit.finance.utils.helper.MullaVersionUpdateHelper
import com.solocredit.finance.utils.helper.SharedHelper
import org.json.JSONArray
import org.json.JSONObject
import java.util.TimeZone


/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/24 11:03
 * @Annotation：启动页面
 */
class MullaSplashAct : MvpAct<IMullaSplashView, MullaSplashPresenterImpl>(), IMullaSplashView {
    lateinit var binding: ActMullaSplashBinding

    private var updateHelper: MullaVersionUpdateHelper? = null
    private val updateLauncher = registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
            // TODO: 更新成功，进入主界面
            showMullaIntentPage()
        } else {
            // 1、用户取消或失败，不处理，继续进入主界面
            // 2、如果需要强制，建议跳转应用商店，拦截进入主界面
            if (updateHelper == null) {
                showMullaIntentPage()
                return@registerForActivityResult
            }
            updateHelper?.handleNoUpdate {
                showMullaIntentPage()
            }
        }
    }

    override fun createPresenter(): MullaSplashPresenterImpl {
        return MullaSplashPresenterImpl(this)
    }

    override fun getMullaRootView(): View {
        binding = ActMullaSplashBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initMullaView() {
        //关闭所有页面
        ActivityStackManager.finishAllActivity(MullaSplashAct::class.java)
        //启动需要重置审核中、放款中显示的公告提示次数
        SharedHelper.saveMullaSPData(SharedHelper.MULLA_SPKEY.MULLA_DIALOG_NOTICE_NUM, 0)
    }

    override fun initMullaListener() {
    }

    override fun initMullaData() {
        showMullaLoading(isTOuchOut = false, isCancel = true)
        // TODO: 坦桑时区需要通过域名获取到IP之后再调时区接口
        if (TimeZone.getDefault().id == "Africa/Dar_es_Salaam"){
            testDNSIpResolver()
        } else {
            presenter.loadMullaTimeZoneAction()
        }

        //牌照信息
        val licenseInfo = MullaCustomConfigsHelper.getMullaLicenseInfo()
        if (licenseInfo == null) {
            binding.licenseLayout.visibility = View.GONE
        } else {
            binding.licenseLayout.visibility = View.VISIBLE
            ImageUtil.instance?.loadImageUrl(this, binding.imgLicenseLogo, licenseInfo.optString("logo"))
            binding.textLicenseDesc.text = licenseInfo.optString("desc")
            binding.textLicenseValue.text = licenseInfo.optString("companyName")
        }
    }

    /**
     * 显示选择语言
     */
    private fun showMullaSplashLanguageDialog() {
        showMullaLanguageDialog("Launch Page", isCancel = false, isCancelTouch = false, onSelectCallback = {
            showMullaConfigSuccess()
        })
    }

    /**
     * 权限说明dialog
     */
    private fun showMullaFlowPermissionReasonDialog(requestCallback: () -> Unit) {
        val perItem = takeMullaPerMSAGItem()
        val reasonDialog = PermissionReasonDialog(this,"Launch Page",object: PermissionReasonDialog.IDialogCallback{
            override fun onDenyClick() {
                HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_PERMISSION_DENY,perItem.optString("permission"))
                requestCallback.invoke()
            }
            override fun onAgreeClick() {
                HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_PERMISSION_AGREE,perItem.optString("permission"))
                requestMullaFlowPermission(perItem ,requestCallback)
            }
        })
        reasonDialog.setCancelable(true)
        reasonDialog.setCanceledOnTouchOutside(false)
        reasonDialog.show()
        reasonDialog.showMullaFlowPermissionItem(perItem)
    }

    /**
     * 授权
     */
    private fun requestMullaFlowPermission(data: JSONObject, requestCallback: () -> Unit){
        val permission = data.optString("permission")
        XXPermissions.with(this)
            // 申请多个权限
            .permission(permission)
            .request(object: OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, p1: Boolean) {
                    if (p1){
                        var permissionString = ""
                        permissions.forEach {
                            permissionString = "$permissionString$it,"
                        }
                        HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_PERMISSION_SYSTEM_AGREE,permissionString.substring(0,permissionString.length - 1))
                        requestCallback.invoke()
                    }
                }
                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    var permissionString = ""
                    permissions.forEach {
                        permissionString = "$permissionString$it,"
                    }
                    HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_PERMISSION_SYSTEM_DENY,permissionString.substring(0,permissionString.length - 1))
                    requestCallback.invoke()
                }
            })
    }

    /**
     * 获取地区转发成功
     */
    override fun showMullaTimeZoneRequestData(dataString: String) {
        var timeZone = ""
        var zoneCode = ""
        var zoneCountry = ""

        dataString.split(",").apply {
            if (this.isNotEmpty()) {
                timeZone = this[0].trim()
            }
            if (this.size >= 2) {
                zoneCode = this[1].trim()
            }
            if (this.size >= 3) {
                zoneCountry = this[2].trim()
            }
        }
        //保存转发地区
        SharedHelper.saveMullaSPData(SharedHelper.MULLA_SPKEY.MULLA_TIMEZONE, timeZone)
        //保存转发地区 区号
        SharedHelper.saveMullaSPData(SharedHelper.MULLA_SPKEY.MULLA_TIMEZONE_CODE, zoneCode)
        //保存国家标识
        SharedHelper.saveMullaSPData(SharedHelper.MULLA_SPKEY.MULLA_TIMEZONE_COUNTRY, zoneCountry)
        //初始化analysis lib 赋值 转发地区
        MullaAnalysisHelper.initAnalysisLibAtZoneSuccess()

        //添加埋点
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_LAUNCH_START)
        //加载客服配置
        presenter.loadMullaCommonConfigAction()
    }

    /**
     * 客服配置获取成功
     */
    override fun showMullaConfigSuccess() {
        val selectedType = SharedHelper.getMullaSPString(SharedHelper.MULLA_SPKEY.MULLA_LANGUAGE_SELECTED_TYPE)
        //坦桑地区 && 没有选择语言
        if (MullaConfigs.isTanz() && selectedType.isEmpty()) {
            showMullaSplashLanguageDialog()
            return
        }

        //是否显示SMS权限声明
        val isShowLaunchPermission = SharedHelper.getMullaSPBoolean(SharedHelper.MULLA_SPKEY.MULLA_PERMISSION_LAUNCH_SHOW)
        if (!isShowLaunchPermission){
            showMullaFlowPermissionReasonDialog{
                SharedHelper.saveMullaSPData(SharedHelper.MULLA_SPKEY.MULLA_PERMISSION_LAUNCH_SHOW,true)
                showMullaConfigSuccess()
            }
            return
        }

        //是否强制更新版本
        val isUpdate = MullaCustomConfigsHelper.isMullaVersionUpdateMust()
        if (isUpdate){
            showMullaVersionUpdateDialog()
            return
        }

        showMullaIntentPage()
    }

    private fun showMullaIntentPage(){
        //已登录 - 进入主页
        if (SharedHelper.getMullaSPBoolean(SharedHelper.MULLA_SPKEY.MULLA_LOGIN)){
            //初始化analysis lib 赋值 用户id 和 token
            MullaAnalysisHelper.initAnalysisLibAtLoginSuccess()
            showMullaMainPage()
        } else {//进入登录页
            showMullaLoginPage()
        }
    }

    /**
     * 进入登录页
     */
    private fun showMullaLoginPage() {
        onIntent(MullaUserLoginAct::class.java)
        finish()
    }

    /**
     * 进入首页
     */
    private fun showMullaMainPage() {
        //保存的时区和当前时区不一致，需要进入登录页面
        if (TimeZone.getDefault().id != SharedHelper.getMullaSPString(SharedHelper.MULLA_SPKEY.MULLA_TIMEZONE_ID)){
            showMullaLoginPage()
            return
        }
        onIntent(MullaMainAct::class.java)
        finish()
    }

    // 测试ip解析
    private fun testDNSIpResolver() {
        try {
            HttpDnsV2().lookupSys2(ApiService.MULLA_BASE_URL) { ipAddr ->
                ApiService.MULLA_BASE_URL = "https://$ipAddr"
                presenter.loadMullaTimeZoneAction()
            }
        } catch (e: Exception){
            e.printStackTrace()
        }
    }

    /**
     * 版本更新Dialog
     */
    private fun showMullaVersionUpdateDialog(){
        val updateDialog = VersionUpdateDialog(this,"Launch page",object : VersionUpdateDialog.IDialogCallback{
            override fun onUpdateClick() {
                try {
                    if (updateHelper == null){
                        updateHelper = MullaVersionUpdateHelper(this@MullaSplashAct, true, updateLauncher)
                    }
                    updateHelper?.checkAndStartUpdate { showMullaIntentPage() }
                } catch (e: Exception) {
                    showMullaIntentPage()
                }
            }
        })
        updateDialog.show()
    }

    /**
     * sms
     */
    fun takeMullaPerMSAGItem(): JSONObject{
        val item = JSONObject()
        item.put("isSystem",true)
        item.put("icon", R.mipmap.mulla_permission_item_sms_icon)
        item.put("permission", Manifest.permission.READ_SMS)
        item.put("title", getString(R.string.permission_msg_title))
        val msgArray = JSONArray()
        val obj1 = JSONObject()
        obj1.put("title", getString(R.string.permission_msg_why))
        obj1.put("des", getString(R.string.permission_msg_why_desc))
        msgArray.put(obj1)

        val obj2 = JSONObject()
        obj2.put("title", getString(R.string.permission_msg_do))
        obj2.put("des", getString(R.string.permission_msg_do_desc))
        msgArray.put(obj2)

        val obj3 = JSONObject()
        obj3.put("title", getString(R.string.permission_msg_data_safety))
        obj3.put("des", getString(R.string.permission_msg_data_safety_desc))
        msgArray.put(obj3)
        item.put("msgList",msgArray)
        return item
    }

    override fun onResume() {
        super.onResume()
        try {
            updateHelper?.resumeIfInProgress()
        } catch (e: Exception) {
            //
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_LAUNCH_END)
    }
}